package com.ruoyi.scheduling.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.scheduling.domain.ASchedulingExecutionVehicle;
import com.ruoyi.scheduling.dto.ADispatchRequestsDTO;
import com.ruoyi.scheduling.form.ADispatchRequestsForm;
import com.ruoyi.scheduling.form.UpdateDispatchRequestsForm;
import com.ruoyi.scheduling.mapper.ASchedulingExecutionVehicleMapper;
import com.ruoyi.system.api.RemoteVehiclesService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.SysVechicleDto;
import com.ruoyi.system.api.domain.SysVehicles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.scheduling.mapper.ADispatchRequestsMapper;
import com.ruoyi.scheduling.domain.ADispatchRequests;
import com.ruoyi.scheduling.service.IADispatchRequestsService;

/**
 * 调度请求Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class ADispatchRequestsServiceImpl implements IADispatchRequestsService 
{
    @Autowired
    private ADispatchRequestsMapper aDispatchRequestsMapper;

    @Autowired
    private RemoteVehiclesService remoteVehiclesService;

    @Autowired
    private ASchedulingExecutionVehicleMapper aSchedulingExecutionVehicleMapper;

    /**
     * 查询调度请求
     * 
     * @param id 调度请求主键
     * @return 调度请求
     */
    @Override
    public ADispatchRequestsDTO selectADispatchRequestsById(Long id)
    {
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectADispatchRequestsId(id);
        if (aDispatchRequests == null) {
            throw new RuntimeException("不存在该申请,请去提交申请");
        }
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(String.valueOf(id), 1L);
        if (aSchedulingExecutionVehicles.isEmpty()){
            throw new RuntimeException("未找到该执行申请记录");
        }
        Set<SysVehicles> sysVehicles = this.getSysVehiclesFromApplicationVehicles(aSchedulingExecutionVehicles);
        // 调用远程服务获取车辆详细信息
        R<Set<SysVechicleDto>> setR = remoteVehiclesService.selectVehicles(sysVehicles);
        if (200 != setR.getCode()) {
            throw new RuntimeException("有车辆信息未找到");
        }
        ADispatchRequestsDTO aDispatchRequestsDTO = new ADispatchRequestsDTO();
        BeanUtil.copyProperties(aDispatchRequests, aDispatchRequestsDTO);
        aDispatchRequestsDTO.setSysVechicleDto(setR.getData());
        return aDispatchRequestsDTO;
    }

    /**
     * 查询调度请求列表
     * 
     * @param aDispatchRequests 调度请求
     * @return 调度请求
     */
    @Override
    public List<ADispatchRequests> selectADispatchRequestsList(ADispatchRequests aDispatchRequests)
    {
        return aDispatchRequestsMapper.selectADispatchRequestsList(aDispatchRequests);
    }
    @Override
    public List<ADispatchRequests> selectADispatchRequestsList(ADispatchRequests aDispatchRequests, SysUser user)
    {
        aDispatchRequests.setCallingOrganizationId(user.getDeptId());
        List<ADispatchRequests> aDispatchRequests1 = aDispatchRequestsMapper.selectADispatchRequestsList(aDispatchRequests);
        aDispatchRequests.setCallingOrganizationId(null);
        aDispatchRequests.setCalledOrganizationId(user.getDeptId());
        List<ADispatchRequests> aDispatchRequests2 = aDispatchRequestsMapper.selectADispatchRequestsList(aDispatchRequests);
        // 合并两个列表
        List<ADispatchRequests> finalList = new ArrayList<>();
        finalList.addAll(aDispatchRequests1);
        finalList.addAll(aDispatchRequests2);

        return finalList;
    }
    @Override
    public List<ADispatchRequests> outbound(ADispatchRequests aDispatchRequests, SysUser user)
    {
        aDispatchRequests.setCallingOrganizationId(user.getDeptId());
        List<ADispatchRequests> aDispatchRequests1 = aDispatchRequestsMapper.selectADispatchRequestsList(aDispatchRequests);
        return aDispatchRequests1;
    }
    @Override
    public List<ADispatchRequests> inbound(ADispatchRequests aDispatchRequests, SysUser user)
    {
        aDispatchRequests.setCalledOrganizationId(user.getDeptId());
        List<ADispatchRequests> aDispatchRequests1 = aDispatchRequestsMapper.selectADispatchRequestsList(aDispatchRequests);
        return aDispatchRequests1;
    }

    /**
     * 新增调度请求
     * 
     * @param aDispatchRequestsForm 调度请求
     * @return 结果
     */
    @Override
    public int insertADispatchRequests(ADispatchRequestsForm aDispatchRequestsForm, SysUser user)
    {
        // 生成唯一的审批请求ID
        String repairNum = new Snowflake(1, 1).nextIdStr();

        // 获取车辆信息并设置状态为已锁定
        Set<SysVehicles> sysVehicles = aDispatchRequestsForm.getSysVehicles();
        // 创建调度申请与车辆关联表对象
        List<ASchedulingExecutionVehicle> schedulingApplicationVehicles = this.createSchedulingApplicationVehicles(repairNum, sysVehicles);
        // 调用远程服务更新车辆状态
        AjaxResult ajaxResult = remoteVehiclesService.updateStatus(sysVehicles);
        if (200 != (int) ajaxResult.get("code")) {
            throw new RuntimeException("有车辆预约失败");
        }
        // 设置审批请求的申请人信息和状态
        aDispatchRequestsForm.setRequesterId(user.getUserId());
        aDispatchRequestsForm.setRequesterName(user.getUserName());
        aDispatchRequestsForm.setDispatchRequestsId(repairNum);
        aDispatchRequestsForm.setDispatchRequestsStatus(0L);
        // 获取当前用户所属部门信息
        aDispatchRequestsForm.setCallingOrganizationId(user.getDeptId());
        aDispatchRequestsForm.setCallingOrganizationName(user.getDept().getDeptName());
        // 将车辆存入调度申请与车辆关联表
        int i = aSchedulingExecutionVehicleMapper.insertASchedulingExecutionVehicleId(schedulingApplicationVehicles);
        if (i != schedulingApplicationVehicles.size()) {
            throw new RuntimeException("有车辆预约失败");
        }
        return aDispatchRequestsMapper.insertADispatchRequests(aDispatchRequestsForm);
    }

    private List<ASchedulingExecutionVehicle> createSchedulingApplicationVehicles(String repairNum, Set<SysVehicles> sysVehicles) {
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = new ArrayList<>();
        for (SysVehicles sysVehicle : sysVehicles) {
            ASchedulingExecutionVehicle aSchedulingExecutionVehicle = new ASchedulingExecutionVehicle();
            aSchedulingExecutionVehicle.setSchedulingExecutionId(Long.valueOf(repairNum));
            aSchedulingExecutionVehicle.setVehicleId(sysVehicle.getId());
            aSchedulingExecutionVehicle.setType(1L);
            aSchedulingExecutionVehicles.add(aSchedulingExecutionVehicle);
            sysVehicle.setStatus(1L);
        }
        return aSchedulingExecutionVehicles;
    }

    /**
     * 修改调度请求
     * 
     * @param param 调度请求
     * @return 结果
     */
    @Override
    public int updateADispatchRequests(UpdateDispatchRequestsForm param, SysUser user)
    {
        // 获取审批请求ID
        Long id = Long.valueOf(param.getDispatchRequestsId());
        checkDispatchRequestExists(id);
        checkDispatchRequestProcessed(id);

        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        // 查询关联的车辆调度申请
        List<ASchedulingExecutionVehicle> aSchedulingApplicationVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(String.valueOf(id), 1L);
        if (aSchedulingApplicationVehicles.isEmpty()) {
            throw new RuntimeException("未找到该申请订单");
        }

        // 获取车辆信息并设置状态为空闲
        Set<SysVehicles> sysVehicles = getSysVehiclesFromApplicationVehicles(aSchedulingApplicationVehicles);
        updateVehicleStatus(sysVehicles, 0L);

        // 更新审批请求状态和拒绝信息
        ADispatchRequests aDispatchRequests = BeanUtil.toBean(param, ADispatchRequests.class);
        aDispatchRequests.setDispatchRequestsStatus(2L);
        aDispatchRequests.setApproverId(user.getUserId());
        aDispatchRequests.setApproverName(user.getUserName());
        System.out.println(aDispatchRequests);
        int i = aDispatchRequestsMapper.updateADispatchRequests(aDispatchRequests);
        if (i == 0) {
            throw new RuntimeException("审批失败");
        }
        return i;
    }

    private Set<SysVehicles> getSysVehiclesFromApplicationVehicles(List<ASchedulingExecutionVehicle> aSchedulingApplicationVehicles) {
        Set<SysVehicles> sysVehicles = new HashSet<>();
        for (ASchedulingExecutionVehicle aSchedulingApplicationVehicle : aSchedulingApplicationVehicles) {
            SysVehicles sysVehicle = new SysVehicles();
            sysVehicle.setId(aSchedulingApplicationVehicle.getVehicleId());
            sysVehicles.add(sysVehicle);
        }
        return sysVehicles;
    }


    /**
     * 批量删除调度请求
     * 
     * @param id 需要删除的调度请求主键
     * @return 结果
     */
    @Override
    public int deleteADispatchRequestsByIds(Long id, SysUser user)
    {
        checkDispatchRequestExists(id);
        checkDispatchRequestProcessed(id);

        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        // 查询关联的车辆调度申请
        List<ASchedulingExecutionVehicle> aSchedulingExecutionVehicles = aSchedulingExecutionVehicleMapper.selectASchedulingExecutionVehicleBySchedulingApplicationId(String.valueOf(id), 1L);
        if (aSchedulingExecutionVehicles.isEmpty()) {
            throw new RuntimeException("未找到该申请订单");
        }

        // 获取车辆信息并设置状态为已批准
        Set<SysVehicles> sysVehicles = getSysVehiclesFromApplicationVehicles(aSchedulingExecutionVehicles);
        updateVehicleStatus(sysVehicles, 2L);

        // 更新审批请求状态和通过信息
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectADispatchRequestsId(id);
        aDispatchRequests.setDispatchRequestsStatus(1L);
        aDispatchRequests.setApproverId(user.getUserId());
        aDispatchRequests.setApproverName(user.getUserName());

        int i = aDispatchRequestsMapper.updateADispatchRequests(aDispatchRequests);
        if (i == 0) {
            throw new RuntimeException("审批失败");
        }

        return i;
    }

    /**
     * 删除调度请求信息
     * 
     * @param id 调度请求主键
     * @return 结果
     */
    @Override
    public int deleteADispatchRequestsById(Long id)
    {
        return aDispatchRequestsMapper.deleteADispatchRequestsById(id);
    }

    /**
     * 检查调度请求是否存在
     *
     * @param id 审批请求主键
     */
    private void checkDispatchRequestExists(Long id) {
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectAApprovalRequestsId(String.valueOf(id));
        if (aDispatchRequests == null) {
            throw new RuntimeException("该申请不存在");
        }
    }

    /**
     * 检查审批请求是否已处理
     *
     * @param id 审批请求主键
     */
    private void checkDispatchRequestProcessed(Long id) {
        ADispatchRequests aDispatchRequests = aDispatchRequestsMapper.selectAApprovalRequestsId(String.valueOf(id));
        if (aDispatchRequests.getDispatchRequestsStatus() != 0) {
            throw new RuntimeException("该申请已处理");
        }
    }

    /**
     * 更新车辆状态
     *
     * @param sysVehicles 车辆集合
     * @param status      车辆状态
     */
    private void updateVehicleStatus(Set<SysVehicles> sysVehicles, long status) {
        for (SysVehicles sysVehicle : sysVehicles) {
            sysVehicle.setStatus(status);
        }

        AjaxResult ajaxResult = remoteVehiclesService.updateStatus(sysVehicles);
        if (200 != (int) ajaxResult.get("code")) {
            throw new RuntimeException("有车辆修改状态失败");
        }
    }
}
